package com.wms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.bean.Category;
import com.wms.bean.Drug;
import com.wms.bean.Supplier;
import com.wms.config.Result;
import com.wms.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("category")
@CrossOrigin
public class CategoryController {
    @Autowired
    CategoryService categoryService;

    @GetMapping("list")
    public Result getList() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }
    @PostMapping("add")
    public Result add(@RequestBody Category category){
        categoryService.save(category);
        Category memberServiceById = categoryService.getById(category.getCid());
        return Result.success("保存成功",memberServiceById);
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") int id){
        boolean b = categoryService.removeById(id);
        if(b){
            return Result.success("删除成功");
        }else{
            return Result.fail(201,"删除失败");
        }
    }
    @PutMapping("update")
    public Result edit(@RequestBody Category category){
        boolean b = categoryService.updateById(category);
        Category member1=categoryService.getById(category.getCid());
        if(b){
            return Result.success("修改成功",member1);
        }else{
            return Result.fail(201,"修改失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        IPage<Category> result;

        if (searchtext == null || searchtext.isEmpty()) {
            result =categoryService.page(page);
        } else {
            QueryWrapper<Category> wrapper = new QueryWrapper<Category>();
            wrapper.like("cid", searchtext)
                    .or().like("cname", searchtext);

            result =categoryService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }

        return Result.success(result);
    }
}
